let username = document.querySelector('.username')
let password = document.querySelector('.password')
let log = document.querySelector('.log')
let remember = document.querySelector('.remember')
let fortnight = document.querySelector('.fortnight')

if (getCookie('checked')) {
  fortnight.checked = getCookie('checked')
}

if (localStorage.getItem('wname')&&localStorage.getItem('wpwd')) {
  username.value = localStorage.getItem('wname')
  password.value = localStorage.getItem('wpwd')
}

// 一进来就判断是否有记住我
if (getCookie('checked') === 'true' && localStorage.getItem('token') !== null) {
  location.href = '../html/index.html' 
}

var flag = true

function fn() {
  if(flag){
    if (username.value == '') {
      username.nextElementSibling.style.display = 'block'
    } else if (password.value == '') {
      password.nextElementSibling.style.display = 'block'
    } else {
      pAjax({
        url: '../server/login.php',
        type: 'post',
        data: {
          username: username.value,
          password: password.value
        }
      }).then(res => {
        if (res == 0) {
          alert('账号或密码错误')
          flag = true
        } else if (res == 1) {
          alert('登录成功')
          localStorage.setItem('token', '8923jsdsdk9sdhosj92ol2')
          localStorage.setItem('rember', remember.checked)
          if(remember.checked){
            localStorage.setItem('wname',username.value)
            localStorage.setItem('wpwd',password.value)
          }else{
            localStorage.removeItem('wname')
            localStorage.removeItem('wpwd')
          }   
          // 记住我的状态
          setCookie('checked', fortnight.checked, 7)
          location.href = '../html/index.html' 
        }
      })
    }
  }
  flag=false

}

log.addEventListener('click', fn)

password.addEventListener('keydown', function (ev) {
  if (ev.keyCode === 13) {
      fn()
  }
})